package com.mucd.chat.service;

import cn.hutool.core.util.ObjectUtil;

import com.mucd.chat.mapper.FriendRequestMapper;
import com.mucd.chat.service.socketService.OnlineSocketService;
import com.mucd.chat.utils.SessionContainer;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.FriendRequest;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class FriendRequestService {

    @Resource
    private FriendRequestMapper friendRequestMapper;
    @Resource
    private OnlineSocketService onlineSocketService;
    @Resource
    private ISysUserService sysUserService;

    @Resource
    private FriendListService friendListService;

    public Object add(FriendRequest friendRequest) {

        if (ObjectUtil.isEmpty(friendRequest)) {
            throw new ServiceException("参数异常!");
        }

        friendRequest.setSendUserId(SecurityUtils.getUserId());
        friendRequest.setStatus(Constants.RELATION_STATUS_PENDING);

        int rows = friendRequestMapper.insert(friendRequest);
        log.info("新增好友请求param:{},结果rows:{}", friendRequest, rows);

        sendSessionMessage(friendRequest);

        return rows;
    }

    /**
     * 发送session消息
     *
     * @param friendRequest 好友请求
     */
    public void sendSessionMessage(FriendRequest friendRequest) {
        //获取对方的session,如果在线则发送添加好友的消息
        Session session = SessionContainer.get(CacheConstants.CHAT_ONLINE_ON_KEY + friendRequest.getReceiveUserId());

        if (ObjectUtil.isNotEmpty(session) && session.isOpen()) {
            LoginUser loginUser = new LoginUser();
            loginUser.setUserId(friendRequest.getReceiveUserId());

            onlineSocketService.selectNotReadNum(loginUser, session);
        }
    }


    /**
     * 查询指定状态的好友请求
     *
     * @param loginUser loginUser
     * @return 好友请求
     */
    public List<FriendRequest> selectByStatusRequestsByReceiverId(LoginUser loginUser) {
        FriendRequest friendRequest = new FriendRequest();
        friendRequest.setStatus(Constants.RELATION_STATUS_PENDING);
        friendRequest.setReceiveUserId(loginUser.getUserId());

        return friendRequestMapper.selectByStatusRequestsByReceiverId(friendRequest);
    }

    /**
     * 查询待同意的请求数量
     * 后续可能会添加群请求数量
     */
    public Object selectRequestCount() {

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(SecurityUtils.getUserId());

        List<FriendRequest> list = this.selectByStatusRequestsByReceiverId(loginUser);
        log.info("查询待同意的请求数量userId:{},结果list:{}", loginUser.getUserId(), list);

        HashMap<String, Integer> resMap = new HashMap<>();
        resMap.put("groupsCount", selectGroupRequestCount());
        resMap.put("friendCount", list.size());

        return resMap;
    }

    public List<FriendRequest> selectFriendRequestList() {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(SecurityUtils.getUserId());

        List<FriendRequest> list = this.selectByStatusRequestsByReceiverId(loginUser);

        //查询头像用户名等信息
        settingUserInfo(list);

        return list;
    }

    /**
     * 群功能待做
     */
    @SuppressWarnings("all")
    public Integer selectGroupRequestCount() {
        List<FriendRequest> list = new ArrayList<>();
        return list.size();
    }

    /**
     * 同意 or 拒绝好友请求
     *
     * @param dto 参数
     * @return 结果
     */
    public Object confirmOrRejectFriend(FriendRequest dto) {

        Long userId = SecurityUtils.getUserId();

        //数据库状态改为 同意Confirmed
        //底部tabbar角标减一条
        dto.setReceiveUserId(userId);

        FriendRequest friendRequest = friendRequestMapper.selectById(dto.getReqId());
        friendRequest.setReceiveUserId(userId);

        List<FriendRequest> list = friendRequestMapper.selectBySendUserIdAndReceiveUserId(friendRequest);

        list.forEach(item -> item.setStatus(dto.getStatus()));

        int rows = friendRequestMapper.confirmOrRejectFriend(list);

        sendSessionMessage(dto);

        if (dto.getStatus().equals(Constants.RELATION_STATUS_CONFIRM)) {
            //双方添加到好友列表
            friendListService.addFriend(friendRequest);
        }

        return rows;
    }

    /**
     * 获取历史请求 拒绝和已同意的
     *
     * @return 结果
     */
    public List<FriendRequest> getRequestHistoryList() {

        FriendRequest friendRequest = new FriendRequest();
        friendRequest.setStatus(Constants.RELATION_STATUS_CONFIRM);
        friendRequest.setReceiveUserId(SecurityUtils.getUserId());

        //查询同意状态的好友请求
        List<FriendRequest> listConfirm = friendRequestMapper.selectByStatusRequestsByReceiverId(friendRequest);

        //查询拒绝状态的好友请求
        friendRequest.setStatus(Constants.RELATION_STATUS_REJECT);
        List<FriendRequest> listReject = friendRequestMapper.selectByStatusRequestsByReceiverId(friendRequest);

        //查询头像用户名等信息
        settingUserInfo(listConfirm);
        settingUserInfo(listReject);

        listConfirm.addAll(listReject);

        return listConfirm;
    }

    /**
     * 设置用户信息 头像用户名等
     *
     * @param list list
     */
    private void settingUserInfo(List<FriendRequest> list) {
        list.stream().parallel().forEach(item -> {
            SysUser sysUser = sysUserService.selectUserById(item.getSendUserId());
            item.setAvatar(sysUser.getAvatar());
            item.setNickName(sysUser.getNickName());
            item.setUserName(sysUser.getUserName());
            item.setPhonenumber(sysUser.getPhonenumber());
        });
    }
}
